﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace XmlSpecParser
{
	public static class XElementExtensions
	{		
		public static IEnumerable<string> GetTexts(this XElement element)
		{
			return element.Nodes().OfType<XText>().Select(x => x.Value);
		}

		public static string GetAttributeValue(this XElement element, XName attributeName)
		{
			var attribute = element.Attribute(attributeName);

			if (attribute == null)
			{
				return null;
			}

			return attribute.Value;
		}

		public static string GetElementValue(this XElement element, params XName[] names)
		{
			foreach (var name in names)
			{
				element = element.Element(name);

				if (element == null)
				{
					return null;
				}
			}

			return element.Value;
		}

		public static string GetElementAttributeValue(this XElement element, params XName[] names)
		{
			for (int i = 0; i < names.Length - 1; i++)
			{
				element = element.Element(names[i]);

				if (element == null)
				{
					return null;
				}
			}

			return element.GetAttributeValue(names.Last());
		}
	}
}
